import { Cookie } from '@/utils/cookieSet';
import { RouteLocationNormalized, NavigationGuardNext } from 'vue-router';
import { useUserInfoStore } from '@/stores/info/index' // 登陆状态获取，全局变量
import { ElMessage } from 'element-plus';

// 白名单，显示轮播图
const RouteWhitelist = ['/login/login','/login/registercounselor','/login/registerClient']

// 咨询师可访问的路由
const CounselorAllowedRoutes = [
  '/counselor/personalInfo',
  '/counselor/rePassword',
  '/counselor/reserveManager',
  '/counselor/reserveSetting',
  '/counselor/articleManager',
]

type RouterGuard = (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => void;

// 定义 beforeEach 路由守卫
const beforeEach: RouterGuard = (to, _from, next) => {
  const userInfoStore = useUserInfoStore(); 
  userInfoStore.restoreState()

  const token = Cookie.getCookies('token');
  const userType = userInfoStore.userInfo.user_type;
  
  // 如果是白名单路由，直接放行
  if (RouteWhitelist.includes(to.path)) {
    next();
    return;
  }

  // 检查是否需要登录权限
  if (!token) {
    // 未登录，跳转到登录页
    ElMessage.warning('请先登录')
    next('/login/login');
    return;
  }

  // 咨询师权限检查
  if (userType === 2) {
    // 如果是咨询师，只允许访问指定路由
    if (!CounselorAllowedRoutes.includes(to.path)) {
      ElMessage.warning('咨询师只能访问个人设置界面')
      next('/counselor/personalInfo');
      return;
    }
  }

  // 检查用户类型权限（如果路由定义了 userType）
  if (to.meta.userType) {
    if (to.meta.userType !== userType) {
      ElMessage.warning('无权访问该页面')
      next(userType === 1 ? '/index' : '/counselor/personalInfo');
      return;
    }
  }

  next();
};

// 定义 afterEach 路由守卫
const afterEach = (to: { path: string; }, _from: any) => {
  // 在导航触发之后执行的逻辑
  // console.log('After each navigation');
  if (!RouteWhitelist.includes(to.path)) {
    // 如果当前路由不在白名单中，滚动条置顶
    window.scrollTo(0, 0);
  }
  if (!Cookie.getCookies('token')) {
    const userInfoStore = useUserInfoStore();
    userInfoStore.setIsLogin(false)
  }
};

export { beforeEach, afterEach, RouteWhitelist };
